{% extends "homepage.html" %}

{% block content %}

<style>
  input.editable {
    border: 1px ;
    text-decoration:none; 
    font-family: sans-serif;
    font-size: 11pt;
    width:100%
  }
  *.editable:hover {
    background-color: #ffffcc;
  }
  textarea.editable {
    border: 1px ;
    text-decoration:none;
    width:100%;
    font-family: monospace;
  }


</style>

<script> 
function parseJsonTable(url, out) {
	jQuery.get(url, function(txt) { parseJsonTable2(txt,out); });
}
function parseJsonTable2(txt, out) {
	var value = JSON.parse(txt.trim().replace(/\n/g, "\\n"));
	var html = '';
	for(var name in value) {
		html += '<h3>' + name + '</h3>';
		html += '<table id="thetable'+name+'" class="tablesorter display" cellpadding="0" cellspacing="0" border="0"></table>';
	}
	out.html(html);
	for(var name in value) {
		var data = value[name].split(/\n/);
		for(var i=0; i<data.length; i++) {
			data[i] = data[i].split(' ');
		}
		var columns = [];
		for(var i=0; i<data[0].length; i++) {
			columns[i] = { "sTitle": "Column " + (i+1) };
		}
		$('#thetable'+name).dataTable( {
		"aaData": data,
		"aoColumns": columns } );	
	}
}

function updateMetadata(id, property, value) {
  jQuery.get("/upload/updateMetadata", {id: id, property: property, value: value});
}

function updateMappingRules(data, id) {
  rules = $('#regexp'+id).val().split(/\n/).filter(function(x) { return x.trim() != ""})

  for(var i=0; i<data.length; i++) {
    data[i][3] = "";
    for(var j=0; j<rules.length/2; j++) {
      re = new RegExp(rules[j+j]);
      sub = rules[j+j+1];
      if(re.test(data[i][2])) {
        data[i][3]=data[i][2].replace(re, sub);
        break;
      }
    }
  }
  $('#table'+id).dataTable( {
    "aaData" : data,
    "aoColumns" : [ {"sTitle" : ""}, {"sTitle" : ""}, {"sTitle" : "Filename"}, {"sTitle" : "Related-to web page"} ],
    "bDestroy" : true
  });
}

</script>


{% macro editable(entry, property) -%}
  {% if current_user.is_admin() or username == entry.metadata['uploader'] -%}
    <input class=editable value="{{entry.metadata[property]}}" onchange="updateMetadata('{{entry._id}}', '{{property}}', this.value)"/>
  {% else %}
    <span class="tex2jax_ignore">{{entry.metadata[property]}}</span>
{%- endif %}
{%- endmacro %}

{% macro editableTextarea(entry, property) -%}
  {% if current_user.is_admin() or username == entry.metadata['uploader'] -%}
    <textarea rows={{entry.metadata[property].count('\n')+1}} class=editable
        onchange="updateMetadata('{{entry._id}}', '{{property}}', this.value)">
{{entry.metadata[property]}}
    </textarea>
  {% else %}
    <pre>
{{entry.metadata[property]}}
    </pre>
  {%- endif %}
{%- endmacro %}


{% macro render_uploadlist(title, list, display) %}
<h2> {{ title }} </h2>

{% for entry in list %}
<p>
<A HREF="#" onclick="$('#display{{entry._id}}').toggle();return false">+{{entry.metadata['name']}}</a>
(uploaded by <A HREF="/users/profile/{{entry.metadata['uploader_id']}}">{{entry.metadata['uploader']}}</A>)<br/>
<dl class=propertylist style="display:{{display}}" id="display{{entry._id}}">
</p>

  <dt>Name</dt>
  <dd>{{editable(entry,'name')}}</dd>

  <dt>Status</dt>
  {% if current_user.is_admin() %}
    <select onchange="updateMetadata('{{entry._id}}', 'status', this.value);return false">
      <option value="approved" {%if entry.metadata.status[0]=='a'%}selected{%endif%}>Approved</option>
      <option value="disapproved" {%if entry.metadata.status[0]=='d'%}selected{%endif%}>Disapproved</option>
      <option value="unmoderated" {%if entry.metadata.status[0]=='u'%}selected{%endif%}>Unmoderated</option>
    </select>
  {% else %}
    <dd>{{entry.metadata.status}}</dd>
  {% endif %}
  <dt>Related to</dt>
  <dd>{{editable(entry,'related_to')}}</dd>
  {% if entry.metadata.parent_archive_id is defined %}
    <dt>Contained in archive</dt>
    <dd><a href="/upload/view/{{entry.metadata.parent_archive_id}}">{{entry.metadata.parent_archive_filename}}</a></dd>
  {% endif %}
  <dt>Original file name</dt>
  <dd>{{editable(entry,'original_file_name')}}</dd>
  <dt>Description</dt>
  <dd>{{editable(entry,'full_description')}}</dd>
  <dt>Data format explanation</dt>
  <dd>{{editable(entry,'data_format')}}</dd>
  <dt>Creator</dt>
  <dd>{{editable(entry,'creator')}}</dd>
  <dt>Paper reference</dt>
  <dd>{{editable(entry,'reference')}}</dd>
  <dt>BibTeX</dt>
  <dd>{{editableTextarea(entry,'bibtex')}}</pre></dd>
  <dt>Comments</dt>
  <dd>{{editableTextarea(entry,'comments')}}</pre></dd>
  <dt>Internal id</dt>
  <dd>{{entry['_id']}}</dd>
  <dt>Contents</dt>
  <dd>

    <a href="{{url_for('.download', id=entry._id, filename=entry.filename)}}">
      Download {{entry.filename}}
    </a>
    <br/>
    <!--<a href="#" onclick="parseJsonTable('/upload/download/{{entry._id}}/{{entry.filename}}', $('#div{{entry._id}}'));return false">
      Parse Json from {{entry.filename}}
    </a>-->
    <a href="#" onclick="$('#div{{entry._id}}').load('{{url_for('.displayParsed',id=entry._id)}}');return false">
      Show automatically parsed data
    </a>

    <div id="div{{entry._id}}">
    </div>
    {% if entry.metadata.content_type == 'text/plain' %}
      <pre>
{{entry.read(10000)}}
      </pre>
    {% elif entry.metadata.content_type == 'image/jpeg' %}
      <img src="{{url_for('.download', id=entry._id, filename=entry.filename)}}"/>
    {% endif %}

    {% if entry.metadata.child_index is defined %}
      <h3>{{KNOWL('uploader.mapping_rules')}} (regular expressions)</h3>
      <textarea cols=100 rows=5 id="regexp{{entry._id}}" onkeyup="updateMappingRules(data{{entry._id}}, '{{entry._id}}')" onchange="updateMappingRules(data{{entry._id}}, '{{entry._id}}')"></textarea>
      <input type=button onclick="jQuery.post('/upload/updateMappingRule', {'id': '{{entry._id}}', 'rule':$('#regexp{{entry._id}}').val().trim().replace(/\$(.)/g,'\\$1')})" value="Update mapping rule">
      
      <table id="table{{entry._id}}" cellpadding="0" cellspacing="0" border="0" class="tablesorter display"></table>
      <script>
        $(document).ready(function() {
          data{{entry._id}} = [
            {% for child in entry.metadata.child_index %}
              [ "<A HREF='{{url_for('.download', id=entry._id, filename=entry.filename+'/'+child[1])}}'>Download</A>",
                "<A HREF='/upload/view/{{child[0]|safe}}'>View</A>",
                "{{child[1] | safe}}",
                ""],
            {% endfor %}
          ];
          updateMappingRules(data{{entry._id}}, "{{entry._id}}");
        });

      </script>
    {% endif %}
  </dd>
  {{ caller(entry) }}
</dl>
{% endfor %}
{% endmacro %}

{% if file is defined %}
{% call(entry) render_uploadlist("View file", [file], '') %}
{% endcall %}
{% endif %}


{% if unmoderated is defined %}

<!--
<script>
  /* attach a submit handler to the form */
  $(document).ready(function() {
   $(".bgpost").submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault(); 
        
    /* get some values from elements on the page: */
    var $form = $( this ),
        id = $form.find( 'input[name="id"]' ).val();
    alert(this.name)

    /* Send the data using post and put the results in a div */
    //$.post( url, { s: term });
   })})
</script>
-->



{% call(entry) render_uploadlist('Awaiting approval', unmoderated, 'none') %}

  <dt>Action</dt>
  <dd>
    <form class="bgpost" action="{{ url_for('.admin_update') }}" method="post">
      <input type="hidden" name="id" value="{{entry._id}}"/>
      <button type="submit" name="approve" value="yes">Approve</button>
      <button type="submit" name="disapprove" value="yes">Disapprove</button>
    </form>
  </dd>
{% endcall %}
{% endif %}


{% if approved is defined %}
  {% call(entry) render_uploadlist('Approved', approved, 'none') %}
  {% endcall %}
{% endif %}

{% if disapproved is defined %}
  {% call(entry) render_uploadlist('Disapproved', disapproved, 'none') %}
  {% endcall %}
{% endif %}

{% if unmoderated2 is defined %}
  {% call(entry) render_uploadlist('Awaiting moderation', unmoderated2, 'none') %}
  {% endcall %}
{% endif %}




{% endblock %}
